# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################
### 景区管理
# Scenic Area Management


from flask import Blueprint
from flask import request
import utils.pgsql.pgcase
import utils.pgsql.pgactivity
import utils.pgsql.pgchannel
import utils.pgsql.pgoperator
import utils.pgsql.pgpoint
import utils.pgsql.pgposition
import utils.pgsql.pgseller
import utils.pgsql.pgtemplate
import utils.pgsql.pgdevice
import utils.pgsql.pgadmin
import requests
from utils.wraps import token, urlcost
import utils.message.response as response
import json
import utils.pgsql.pgdevice as device
import utils.common.httpclient as httpclient


case_module = Blueprint("base_case", __name__, url_prefix="/api/v1/scenic/case")

# 获取景区列表
@case_module.route("/admin/<int:adminId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def case_all(adminId):
 
    case_obj = utils.pgsql.pgcase.PgCase()
    
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    # {'adminId': 1, 'operatorId': 0, 'caseId': 0, 'role': 1}

    if userInfo["role"] in [1,0,4,5]: #4是客服,5是财务
        return response.make_response_success(case_obj.all())
    if userInfo["role"] in [2]:
        operatorId = userInfo["operatorId"]

        return response.make_response_success(case_obj.allByOperator(operatorId))
    if userInfo["role"] in [3]:
        obj_admin = utils.pgsql.pgadmin.PgAdmin()
        caseId = obj_admin.get_caseId(adminId)["caseId"]
        return response.make_response_success(case_obj.getBycaseId(caseId))
    if userInfo["role"] in [6]:# 城市区域账号
        obj_admin = utils.pgsql.pgadmin.PgAdmin()
        case_list = obj_admin.get_city_cases(adminId)['caseName']
        all_case = case_obj.all()
        res = [i for i in all_case if i['caseName'] in case_list]
        return response.make_response_success(res)
    else:
        return response.make_response_401()

# to algo
@case_module.route("/admin/caseGet", methods=["GET"])
@urlcost.cost_count_wraps
def case_allget():
 
    case_obj = utils.pgsql.pgcase.PgCase()
    res = case_obj.allget()
    if res:
        return response.make_response_success(res)
    else:
        return response.make_response_401()
    
# to algo 景区数据同步接口
@case_module.route("/synchronization", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def synchronization():
 
    case_obj = utils.pgsql.pgcase.PgCase()
    # 调用博观接口
    ret, res_data = httpclient.synchronization_getCase()

    if ret:
        # for i in range(res_data[-1]["caseId"]):
        #     case_obj.add({"caseName":""})  # 插入 createTime
        # for i in range(res_data[-1]["caseId"]+1):
        #         case_obj.delete(i)  # 根据 caseid 删除已有数据
        for i in res_data:
            if int(i['states']) == 1:
                i["auditstatus"] ="审核成功"
            case_res = case_obj.add(i)
        return response.make_response_success_no_data()
    else:
        return response.make_response_401()
    
# to algo
@case_module.route("/other/synchronization/<int:type>", methods=["GET"])
@urlcost.cost_count_wraps
def other_synchronization(type):
    ret, res_data = httpclient.synchronization_getother(type)
    if ret:
        if type == 1:
            obj = utils.pgsql.pgactivity.PgActivity()
            for i in range(res_data[-1]["activityId"]):
                res_data1 = obj.add({"activityName":""})
            for i in range(res_data[-1]["activityId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.add(i)
        elif type == 2:
            obj = utils.pgsql.pgadmin.PgAdmin()
            for i in range(res_data[-1]["adminId"]):
                res_data1 = obj.addAdmin({"name":""})
            for i in range(res_data[-1]["adminId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.addAdmin(i)
        elif type == 3:
            obj = utils.pgsql.pgchannel.PgChannel()
            for i in range(res_data[-1]["channelId"]+30):
                res_data1 = obj.addChannel({"channelName":""})
            for i in range(res_data[-1]["channelId"]+31):
                obj.delete(i)
            for i in res_data:
                obj.addChannel(i)
        elif type == 4:
            obj = utils.pgsql.pgoperator.PgOperator()
            for i in range(res_data[-1]["operatorId"]):
                res_data1 = obj.addOperator({"operatorName":""})
            for i in range(res_data[-1]["operatorId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.addOperator(i)
        elif type == 5:
            obj = utils.pgsql.pgpoint.PgPoint()
            for i in range(res_data[-1]["pointId"]):
                res_data1 = obj.add({"pointName":""})
            for i in range(res_data[-1]["pointId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.addPoint(i)
        elif type == 6:
            obj = utils.pgsql.pgposition.PgPosition()
            for i in range(res_data[-1]["positionId"]):
                res_data1 = obj.add({"operatorName":""})
            for i in range(res_data[-1]["positionId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.add(i)
        elif type == 7:
            obj = utils.pgsql.pgseller.PgSeller()
            for i in range(res_data[-1]["sellerId"]):
                res_data1 = obj.addseller({"firmName":""})
            for i in range(res_data[-1]["sellerId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.addseller(i)
        elif type == 8:
            obj = utils.pgsql.pgtemplate.PgTemplate()
            for i in range(res_data[-1]["templateId"]):
                res_data1 = obj.addTemplate({"templateName":""})
            for i in range(res_data[-1]["templateId"]+1):
                obj.delete(i)
            for i in res_data:
                obj.addTemplate(i)
    return response.make_response_success_no_data()



@case_module.route("/operatorId/<int:operatorId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def operatorId_all(operatorId):
    print(operatorId)
 
    case_obj = utils.pgsql.pgcase.PgCase()
    
    print(case_obj.allByOperator(operatorId))
    return response.make_response_success(case_obj.allByOperator(operatorId))

# 新增景区
@case_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def case_add():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [2,1,0]:
        obj = utils.pgsql.pgcase.PgCase()
        info = json.loads(request.data)

        res = obj.add(info)
        if res == {}:
            return response.make_response_1505()
        return response.make_response_success(res)
    else:
        return response.make_response_401()

# 根据景区id 获取某个景区的详情
@case_module.route("/<int:caseID>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def case_get(caseID):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1,0]:
        obj = utils.pgsql.pgcase.PgCase()
        return response.make_response_success(obj.get(caseID))
    else:
        return response.make_response_401()

# 修改景区
@case_module.route("/<int:caseId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def case_put(caseId):


    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [0,1, 2, 3]:
        obj = utils.pgsql.pgcase.PgCase()
        dic = json.loads(request.data)
        # deviceobj = device.PgDevice()
        # res = deviceobj.allByCase(caseId)
        # # 
        # caseold = obj.getBycaseId(caseId)
        # if caseold[0]["svraddr"] != dic["svraddr"] and caseold[0]["svraddr"] !="":
        #     try:
        #         res_value = requests.get(
        #                             "http://"+ str(caseold[0]["svraddr"])+":36780"
        #                             + "/api/v1/channel/all",
        #                             headers={
        #                                 "content-type": "application/json",
        #                                 "Authorization": "ztdasfwadfasdfd",
        #                             }
        #                         )
        #                  
        #         res_value1 = json.loads(res_value.text)
        #         for i in res:
        #             # dic["devicealgoId"] = -1
        #             for j in res_value1["data"]:
        #                 if j["gbcode"] == i["deviceGbCode"]:
        #                     url = "http://127.0.0.1:33033/api/v1/scenic/device/algo/" + str(i["deviceId"])
        #                     header = {
        #                         "content-type": "application/json",
        #                     }
        #                     ret = requests.get(url, headers=header, timeout=5)
        #                     ret = json.loads(ret.text)["data"]["data"][0]
        #                     del ret["id"]
        #                     deviceobj.modify(i["deviceId"], {"isfparams":json.dumps(ret)})
        #                     requests.delete(
        #                         "http://"+ str(caseold[0]["svraddr"])+":36780" + "/api/v1/channel/" + str(j["id"]),
        #                         headers={
        #                             "content-type": "application/json",
        #                             "Authorization": "ztdasfwadfasdfd",
        #                         },
        #                     )
        #                     deviceobj.modify(i["deviceId"], {"devicealgoId":"-1"})
        #                     break
        #     except:
        #         print("error")           


        #  
        # deviceIp = "http://"+ str(dic["svraddr"])+":36780"
        #  
        # if dic["state"] == "3":
        #      
        #     try:
        #         res_value = requests.get(
        #                             deviceIp
        #                             + "/api/v1/channel/all",
        #                             headers={
        #                                 "content-type": "application/json",
        #                                 "Authorization": "ztdasfwadfasdfd",
        #                             }
        #                         )
        #                 
        #         res_value1 = json.loads(res_value.text)
        #         for i in res:
        #             # dic["devicealgoId"] = -1
        #             for j in res_value1["data"]:
        #                 if j["gbcode"] == i["deviceGbCode"]:
        #                     url = "http://xxxxx:xxxxx/api/v1/scenic/device/algo/" + str(i["deviceId"])
        #                     header = {
        #                         "content-type": "application/json",
        #                     }
        #                     ret = requests.get(url, headers=header, timeout=5)
        #                     ret = json.loads(ret.text)["data"]["data"][0]
        #                     del ret["id"]
        #                     deviceobj.modify(i["deviceId"], {"isfparams":json.dumps(ret),"state":"0"})
        #                     requests.delete(
        #                         deviceIp + "/api/v1/channel/" + str(j["id"]),
        #                         headers={
        #                             "content-type": "application/json",
        #                             "Authorization": "ztdasfwadfasdfd",
        #                         },
        #                     )
        #                     deviceobj.modify(i["deviceId"], {"devicealgoId":"-1"})
        #                     break
        #     except:
        #         return response.make_response_1006()
        # else:
        #     # 
        #     for i in res:
        #         try:
        #             res_value = requests.get(
        #                 deviceIp
        #                 + "/api/v1/channel/all",
        #                 headers={
        #                     "content-type": "application/json",
        #                     "Authorization": "xxxxxxxxxxxxxxxxx",
        #                 }
        #             )
        #             # 
        #             res_value1 = json.loads(res_value.text)
        #                 # dic["devicealgoId"] = -1
        #             for j in res_value1["data"]:
        #                 if j["gbcode"] != i["deviceGbCode"] and j==res_value1["data"][-1]:
        #                     url = "http://127.0.0.1:33033/api/v1/scenic/device/algo/add"
        #                     header = {
        #                         "content-type": "application/json",
        #                     }
        #                     dic1 = {
        #                         "deviceIp": deviceIp,
        #                         "deviceName":i["deviceName"],
        #                         "streamType": i["streamType"],
        #                         "deviceGbCode": i["deviceGbCode"],
        #                         "deviceId":str(i["deviceId"])
        #                     }
        #                     ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=5)
        #                     ret = json.loads(ret.text)
        #                     if ret[0] == "False":
        #                         if ret[1] == "1006":
        #                             return response.make_response_1006()
        #                         elif ret[1] == "1007":
        #                             return response.make_response_1007()
        #                     else:
        #                         url = "http://127.0.0.1:33033/api/v1/scenic/algo/smart/" + str(i["deviceId"])
        #                         header = {
        #                             "content-type": "application/json",
        #                         }
        #                         dic1 = {
        #                             "facedetection": i["isfparams"]["rules"][0]["event"],
        #                             "points":i["isfparams"]["rules"][0]["points"],
        #                             "vlogdata": i["isfparams"]["params"],
        #                         }
        #                         ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=60)
        #                         ret = json.loads(ret.text)
        #                         deviceobj.modify(i["deviceId"], {"state":"1"})
        #                 elif j["gbcode"] == i["deviceGbCode"] :
        #                     break
        #         except:
        #             return response.make_response_1006()
        #         # url = "http://127.0.0.1:33033/api/v1/scenic/device/algo/add"
        #         # header = {
        #         #     "content-type": "application/json",
        #         # }
        #         # dic1 = {
        #         #     "deviceIp": deviceIp,
        #         #     "deviceName":i["deviceName"],
        #         #     "streamType": i["streamType"],
        #         #     "deviceGbCode": i["deviceGbCode"],
        #         #     "deviceId":str(i["deviceId"])
        #         # }
        #         # ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=5)
        #         # ret = json.loads(ret.text)
        #         # if ret[0] == "False":
        #         #     if ret[1] == "1006":
        #         #         return response.make_response_1006()
        #         #     elif ret[1] == "1007":
        #         #         return response.make_response_1007()
        #         # else:
        #         #     url = "http://127.0.0.1:33033/api/v1/scenic/device/algo/" + str(i["deviceId"])
        #         #     header = {
        #         #         "content-type": "application/json",
        #         #     }
        #         #     dic1 = {
        #         #         "facedetection": i["isfparams"]["rules"][0]["event"],
        #         #         "points":i["isfparams"]["rules"][0]["points"],
        #         #         "vlogdata": i["isfparams"]["params"],
        #         #     }
        #         #     ret = requests.post(url, headers=header, data=json.dumps(dic1), timeout=30)
        #         #     ret = json.loads(ret.text)

        if obj.modify(dic, "caseId", caseId):
            # 如果改了景区简称，需要同时修改对应的模板及活动

            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@case_module.route("/state", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def case_enable():

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1,0]:
        dic = json.loads(request.data)
        obj = utils.pgsql.pgcase.PgCase()
        if obj.updateState(dic["state"], dic["caseId"]):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@case_module.route("/delete", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def case_soft_delete():

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    dic = json.loads(request.data)
    if userInfo["role"] in [1,0] :
        obj = utils.pgsql.pgcase.PgCase()
        adminobj = utils.pgsql.pgadmin.PgAdmin()

        if obj.soft_delete(dic["caseId"], obj.get_caseName(dic["caseId"])["caseName"]):
            # adminobj.casedelete(dic["caseId"])

            # adminobj = utils.pgsql.pgadmin.PgAdmin()
            # adminobj.casedelete(dic["caseId"])

            # deviceobj = utils.pgsql.pgdevice.PgDevice()
            # devicedeletes = deviceobj.allByCase_streamType(
            #     dic["caseId"]
            # )  
            # devicedelete = []
            # for i in devicedeletes:
            #     if i not in devicedelete:
            #         devicedelete.append(i) 
            # allstreamType = deviceobj.allstreamType()  
            # for i in devicedelete:  
            #     if i not in allstreamType:
            #         url = "http://127.0.0.1:33033/api/v1/scenic/device/delete"
            #         header = {
            #             "content-type": "application/json",
            #             "Authorization": "ZTAI5t7StH4JsKGysZfb2XgT",
            #         }
            #         res = requests.post(
            #             url,
            #             json.dumps(
            #                 {
            #                     "deviceIp": i["deviceIp"],
            #                     "deviceAiboxId": i["deviceAiboxId"],
            #                 }
            #             ),
            #             headers=header,
            #             timeout=5,
            #         )

            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    # elif dic["operatorId"] in [1, 2]:
    #     return response.make_response_error_1500()
    else:
        return response.make_response_401()




# 获取景区审核状态的列表 auditstatus
@case_module.route("/case_auditstatus",methods=["GET"])
@token.login_required
def case_auditstatus():
    case_obj = utils.pgsql.pgcase.PgCase()
    res = case_obj.case_AIstates_sql()
    if res:
        # for one_date in res:
        #     # print("one_date",one_date)
        #     if one_date.get("auditstatus","")=="审核成功":
        #         one_date["auditstatus"]='1'
        #     elif one_date.get("auditstatus","")=="未审核":
        #         one_date["auditstatus"]='3'
        #     else: # 审核失败
        #         one_date["auditstatus"] = '4'

        return response.make_response_success(res)
    else:
        return response.make_response_401()


# 修改景区上线下线状态
@case_module.route("/case_states", methods=["POST"])
@token.login_required
def POST_case_states():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    dic = json.loads(request.data)
    print("dic",dic)
    if userInfo["role"] in [1,0]:
        obj = utils.pgsql.pgcase.PgCase()
        if obj.update_auditstatus_State(dic["auditstatus"],dic["states"], dic["caseId"]):
            resp = response.make_response_success_no_data()

            resp.headers['Access-Control-Allow-Methods'] = 'GET,POST'
            resp.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'

            return resp
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()




# 景区逻辑删除
@case_module.route("/case_delete", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def case_delete():

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    dic = json.loads(request.data)
    if userInfo["role"] in [1,0] :
        obj = utils.pgsql.pgcase.PgCase()

        if obj.case_delete_sql(dic["caseId"]):

            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@case_module.route("/case_device/", methods=["GET", "POST"])
# @token.login_required
@urlcost.cost_count_wraps
def all_case_device():
    # 大屏接口
    obj = utils.pgsql.pgcase.PgCase()
    if request.method == "POST":
        dic = json.loads(request.data)
        # {"state":"true"} or {"state":"false"}
        state = dic.get("state")
        if "state" in dic:
            res = obj.get_online_device(state)
            for i in res:
                i['full_name'] = "{}-{}".format(i["caseName"],i["deviceId"])
            return response.make_response_success(res)
    res = obj.get_online_device()
    return response.make_response_success(res)


@case_module.route("/cases_status/", methods=["GET"])
# @token.login_required
@urlcost.cost_count_wraps
def cases_status():
    # 所有景区上线状态, 供大屏使用
    obj = utils.pgsql.pgcase.PgCase()
    total, online, offline = obj.get_cases_status()
    data = {
        "total":total,
        "online": online,
        "offline":offline
    }
    return response.make_response_success(data)


@case_module.route("/address", methods=["GET"])
# @token.login_required
@urlcost.cost_count_wraps
def all_case_address():
    # 大屏接口 省和坐标
    obj = utils.pgsql.pgcase.PgCase()
    res = obj.getaddress()
    ruturn_list =[]
    address_split_lsit =["浙江省"]
    for one_dic in res:
        address_str = one_dic.get("address")

        if "省" in address_str:
            address_split = address_str.split("省")[0] + "省"

        elif "自治" in address_str:
            address_split = address_str.split("自治")[0] + "自治区"

        elif "市" in address_str:
            address_split = address_str.split("市")[0] + "市"

        elif "区" in address_str:
            address_split = address_str.split("区")[0] + "区"


        else:
            address_split = address_str


        if address_split in address_split_lsit:
            continue
        else:
            address_split_lsit.append(address_split)
            one_dic["address_split"] = address_split
            ruturn_list.append(one_dic)

    return response.make_response_success(ruturn_list)







